package ch.usi.inf.pf2.gui;

import java.io.IOException;

import ch.usi.inf.pf2.ReadSpreadSheetFile;
import ch.usi.inf.pf2.Sheet;
import ch.usi.inf.pf2.WriteSpreadSheetFile;

/**
 * SpreadSheetFileManager class opens and saves CSV files.
 * 
 * @author Ebrisa Savina Mastrodicasa
 * 
 */

public class SpreadSheetFileManager {

	/**
	 * Load from disk a spreadsheet file and open it.
	 * 
	 * @param fileName
	 *            The name of the CSV file to be opened.
	 * @return The spreadsheet in the file or null if it does not exist.
	 */
	public static Sheet openFile(String fileName) {
		try {
			ReadSpreadSheetFile rssf = new ReadSpreadSheetFile(fileName);
			Sheet spreadSheetRead = rssf.readSheet();
			if (spreadSheetRead == null) {
				return null;
			}
			return spreadSheetRead;
		} catch (IOException e) {
			return null;
		}
	}

	/**
	 * Write a CSV file to disk under a default name.
	 * 
	 * @param sheetToSave
	 *            The Sheet object to be saved.
	 * @param fileName
	 *            The default name for the CSV file.
	 */
	public static void saveFile(Sheet sheetToSave, String defaultName) {
		WriteSpreadSheetFile wssf = new WriteSpreadSheetFile(sheetToSave,
				defaultName);
		wssf.writeSheet();
	}

	/**
	 * Write a CSV file to disk under a name chosen by the user.
	 * 
	 * @param sheetToSave
	 *            The Sheet object to be saved.
	 * @param fileName
	 *            The name wanted for the CSV file.
	 */
	public static void saveAsFile(Sheet sheetToSave, String fileName) {
		WriteSpreadSheetFile wssf = new WriteSpreadSheetFile(sheetToSave,
				fileName);
		wssf.writeSheet();
	}

}
